package com.tubeonfire.model.admin;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TreeMap;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.tubeonfire.entity.Tube;
import com.tubeonfire.search.admin.TubeSearchEngine;

public class TubeModel {

	private static Objectify ofy;

	private static Cache cache = null;

	private static boolean isRegisted = false;

	private static ObjectifyOpts opts = null;

	private static String cacheSide = "backEnd_";

	private static String cachePrefix = "tubeModel_";

	private static TreeMap<String, String> mapCacheKey = new TreeMap<String, String>();

	private int limit = 10;

	private int page = 1;

	private int totalResult = 0;

	private int totalPage = 1;

	private List<Tube> listResult = new ArrayList<Tube>();

	public int getTotalPage() {
		totalPage = totalResult / limit;
		if ((totalResult % limit) > 0) {
			totalPage += 1;
		}
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getTotalResult() {
		return totalResult;
	}

	public void setTotalResult(int totalResult) {
		this.totalResult = totalResult;
	}

	public List<Tube> getListResult() {
		return listResult;
	}

	public void setListResult(List<Tube> listResult) {
		this.listResult = listResult;
	}

	public static void init() {
		if (!isRegisted) {
			isRegisted = true;
			try {
				ObjectifyService.register(Tube.class);
			} catch (Exception e) {
				isRegisted = false;
			}
			try {
				cache = CacheManager.getInstance().getCacheFactory()
						.createCache(Collections.emptyMap());
			} catch (CacheException e) {
				isRegisted = false;
			}
			opts = new ObjectifyOpts().setSessionCache(true);
		}
		ofy = ObjectifyService.begin(opts);
	}

	public TubeModel() {
		init();
	}

	@SuppressWarnings("unchecked")
	public static void insert(Tube obj) {
		init();
		if (cache != null) {
			cache.put(cachePrefix + "id_" + obj.getId(), obj);
		}
		ofy.put(obj);
		TubeSearchEngine.update(obj);
		clearModelCache();
		com.tubeonfire.search.TubeSearchModel.clearModelCache();
		com.tubeonfire.model.TubeModel.clearModelCache();
	}

	@SuppressWarnings("unchecked")
	public static void insertNoIndex(Tube obj) {
		init();
		if (cache != null) {
			cache.put(cachePrefix + "id_" + obj.getId(), obj);
		}
		ofy.put(obj);
		clearModelCache();
		com.tubeonfire.search.TubeSearchModel.clearModelCache();
		com.tubeonfire.model.TubeModel.clearModelCache();
	}

	@SuppressWarnings("unchecked")
	public static void update(Tube obj) {
		init();
		if (cache != null) {
			String prefix = cachePrefix + "id_" + obj.getId();
			cache.put(prefix, obj);
		}
		ofy.put(obj);
		TubeSearchEngine.update(obj);
		clearModelCache();
		com.tubeonfire.search.TubeSearchModel.clearModelCache();
		com.tubeonfire.model.TubeModel.clearModelCache();
	}

	@SuppressWarnings("unchecked")
	public static void insert(List<Tube> listObj) {
		init();
		ofy.put(listObj);
		for (Tube tube : listObj) {
			String prefix = cachePrefix + "id_" + tube.getId();
			cache.put(prefix, tube);
			TubeSearchEngine.update(tube);
		}
		clearModelCache();
		com.tubeonfire.search.TubeSearchModel.clearModelCache();
		com.tubeonfire.model.TubeModel.clearModelCache();
	}

	public static void delete(Tube obj) {
		init();
		String prefix = cachePrefix + "id_" + obj.getId();
		if (cache != null && cache.containsKey(prefix)) {
			cache.remove(prefix);
		}
		ofy.delete(obj);
		TubeSearchEngine.remove(obj.getId());
		clearModelCache();
		com.tubeonfire.search.TubeSearchModel.clearModelCache();
		com.tubeonfire.model.TubeModel.clearModelCache();
	}

	@SuppressWarnings("unchecked")
	public static Tube getById(String id, boolean fromCache) {
		try {
			init();
			Tube obj = new Tube();
			String prefix = cachePrefix + "id_" + id;
			if (cache != null && cache.containsKey(prefix) && fromCache) {
				obj = (Tube) cache.get(prefix);
			} else {
				try {
					obj = ofy.get(new Key<Tube>(Tube.class, id));
					if (fromCache) {
						cache.put(prefix, obj);
					}
				} catch (Exception e) {
					obj = null;
				}
			}
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	@SuppressWarnings("unchecked")
	public void getTubes(boolean fromCache) {
		init();
		listResult = new ArrayList<Tube>();
		String prefix = cacheSide + cachePrefix + "tubes_" + page;
		mapCacheKey.put(prefix, prefix);
		if (cache != null && cache.containsKey(prefix) && fromCache) {
			listResult = (ArrayList<Tube>) cache.get(prefix);
		} else {
			int start = (page - 1) * limit;
			Query<Tube> q = ofy.query(Tube.class).order("-updated");
			totalResult = q.count();
			q = q.limit(limit).offset(start);
			for (Tube tub : q) {
				listResult.add(tub);
			}
			if (listResult.size() > 0 && fromCache) {
				cache.put(prefix, listResult);
			}
		}
	}

	@SuppressWarnings("unchecked")
	public void getByPlaylist(String playlistId) {
		init();
		listResult = new ArrayList<Tube>();
		String prefix = cacheSide + cachePrefix + "category_" + playlistId
				+ page;
		mapCacheKey.put(prefix, prefix);
		if (cache != null && cache.containsKey(prefix)) {
			listResult = (List<Tube>) cache.get(prefix);
		} else {
			int start = (page - 1) * limit;
			Query<Tube> q = ofy.query(Tube.class)
					.filter("playlistId", playlistId).order("updated");
			totalResult = q.count();
			q = q.limit(limit).offset(start);
			for (Tube tub : q) {
				listResult.add(tub);
			}
			if (listResult.size() > 0) {
				cache.put(prefix, listResult);
			}
		}
	}

	@SuppressWarnings("unchecked")
	public void search(String keyword) {
		init();
		listResult = new ArrayList<Tube>();
		String prefix = cacheSide + cachePrefix + "keyword_" + keyword + page;
		mapCacheKey.put(prefix, prefix);
		if (cache != null && cache.containsKey(prefix)) {
			listResult = (List<Tube>) cache.get(prefix);
		} else {
			int start = (page - 1) * limit;
			Query<Tube> q = ofy.query(Tube.class).filter("title", keyword)
					.order("updated");
			totalResult = q.count();
			q = q.limit(limit).offset(start);
			for (Tube tub : q) {
				listResult.add(tub);
			}
			if (listResult.size() > 0) {
				cache.put(prefix, listResult);
			}
		}
	}

	public static void clearModelCache() {
		init();
		try {
			if (mapCacheKey != null && mapCacheKey.size() > 0) {
				for (String key : mapCacheKey.keySet()) {
					cache.remove(key);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
